package com.jeff.android.lab.architecture.eventbus;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.jeff.android.lab.R;
import com.jeff.android.lab.architecture.eventbus.event.MessageEvent;
import com.jeff.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.OnClick;

/**
 * @author: duff
 * @date: 2019/4/3
 * @since: 1.0.0
 */
public class EventBusFragment extends EventBusBaseFragment {

    @Override
    protected int getRootLayout() {
        return R.layout.architecture_fragment_eventbus;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMain(MessageEvent event) {

        Log.d(TAG, "EventBusFragment.onEventMain");

        if (event.id == 1000) {
            String result = (String) event.object;
            ToastUtil.show(mContext, result);
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onEventBackground(MessageEvent event) {
        if (event.id == 1001) {
            String result = (String) event.object;
            ToastUtil.show(mContext, "线程：" + Thread.currentThread().getName() + " 接收：" + result);
        }
    }

    @OnClick({R.id.bt1, R.id.bt2})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt1:
                EventBus.getDefault().post(new MessageEvent(1000, "Hello, World!!!"));
                break;

            case R.id.bt2:
                EventBus.getDefault().post(new MessageEvent(1001, "Hello, World!!!"));
                break;

            case R.id.bt3:
                EventBus.getDefault().post(new MessageEvent(1002, "Hello, World!!!"));
                break;
        }
    }

}
